package com.ygxsk.carhome.ui.insurance;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.flyco.roundview.RoundTextView;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.alertview.AlertView;
import com.ygxsk.carhome.alertview.OnItemClickListener;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.enumwrap.CallHistoryBusinessType;
import com.ygxsk.carhome.enumwrap.CarRenewalStatus;
import com.ygxsk.carhome.event.EventCarInsuranceDetail;
import com.ygxsk.carhome.event.EventCarInsuranceMain;
import com.ygxsk.carhome.listener.Delivery;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.response.CarInsuranceBean;
import com.ygxsk.carhome.response.CarInsuranceDetailBean;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.utils.StringCodeUtils;
import com.ygxsk.integrated.retrofit.Parameterkey;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;

import butterknife.BindView;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023-09-20  14:29
 * @Description:
 */
public class CarInsuranceDetailActivity extends ErrorActivity implements ErrorParentExtraSingle {


    @BindView(R.id.refreshLayoutInInsuranceDetail)
    SmartRefreshLayout refreshLayoutInInsuranceDetail;

    //联系人姓名
    @BindView(R.id.textViewPersonValueInsuranceDetail)
    TextView textViewPersonValueInsuranceDetail;

    //状态值
    @BindView(R.id.textViewPersonOrderStateInsuranceDetail)
    TextView textViewPersonOrderStateInsuranceDetail;

    //联系人 手机号
    @BindView(R.id.textViewPersonPhoneValueInsuranceDetail)
    TextView textViewPersonPhoneValueInsuranceDetail;

    //联系人 车牌号
    @BindView(R.id.textViewCarNumberValueInsuranceDetail)
    TextView textViewCarNumberValueInsuranceDetail;

    //联系人 创建时间
    @BindView(R.id.textViewCreateTimeInsuranceDetail)
    TextView textViewCreateTimeInsuranceDetail;

    //包裹两个按钮的布局
    @BindView(R.id.relativeLayoutTwoButtonInsuranceDetail)
    RelativeLayout relativeLayoutTwoButtonInsuranceDetail;

    @BindView(R.id.roundTextViewViewTakeOrderInsuranceDetail)
    RoundTextView roundTextViewViewTakeOrderInsuranceDetail;

    @BindView(R.id.roundTextViewViewCompleteOrderInsuranceDetail)
    RoundTextView roundTextViewViewCompleteOrderInsuranceDetail;

    //携带过来的 对于 一键出险的 列表条目实体；
    private CarInsuranceBean extra_car_insurance_list_item_bean;

    //该单据的 详情 id 为了获取接口；
    private Integer extra_car_lossAdviceId;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        processExtraData();

        initloading();

        initViews();

        gainDatas();

        //这里有页面刷新，或者编辑完毕，通知页面刷新的逻辑；
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_car_insurance_detail;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();

    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

//        toolbarHelper.setLayoutSao(false, null);
        toolbarHelper.setTitle(getString(R.string.title_detail_insurance));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //checkEdit();
                methodBack();
            }
        });

        toolbarHelper.setLayoutClose(false, "", null);

        //右侧是【编辑】
        toolbarHelper.setLayoutRight(false, 0, "", null);

//        toolbarHelper.setLayoutRight(false, 0, getString(R.string.button_edit_right), new ClickUtils.OnDebouncingClickListener() {
//            @Override
//            public void onDebouncingClick(View v) {
//
//                //携带信息跳转到【编辑-提交】页面；
//                Bundle extra_bundle = new Bundle();
//
//                //携带 订单的id，获取一次详情，再修改
//
//                ActivityUtils.startActivity(extra_bundle, LeadAddSubmitActivity.class);
//
//            }
//        });

    }

    @Override
    protected void onClickNodata(View v) {

        gainDatas();

    }

    @Override
    protected void initViews() {

        refreshLayoutInInsuranceDetail.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        gainDatas();

                        refreshLayout.finishRefresh();

                    }
                });

            }
        });

        //接单 按钮
        if (roundTextViewViewTakeOrderInsuranceDetail != null) {

            roundTextViewViewTakeOrderInsuranceDetail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    CommUtils.checkDialog(mAlertView);
                    mAlertView = new AlertView(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //提示
                            StringUtils.getString(R.string.submit_carrenewal_takeorder_message),//提示内容 确定接单
                            StringUtils.getString(R.string.clearcachecancel), //取消
                            new String[]{StringUtils.getString(R.string.clearaddorsubmitsure)},//确定
                            null, mActivityInstance, AlertView.Style.Alert, new OnItemClickListener() {//
                        @Override
                        public void onItemClick(Object o, int position) {

                            if (position != AlertView.CANCELPOSITION) {

                                method_gainTakeOrderSubmitInfo_upLoad(extra_car_lossAdviceId);

                            }

                        }
                    });

                    mAlertView.setCancelable(true);
                    mAlertView.show();

                }
            });
        }

        //完成 按钮

        if (roundTextViewViewCompleteOrderInsuranceDetail != null) {

            roundTextViewViewCompleteOrderInsuranceDetail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    CommUtils.checkDialog(mAlertView);
                    mAlertView = new AlertView(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //提示
                            StringUtils.getString(R.string.submit_carrenewal_completeorder_message),//提示内容 确定审核通过
                            StringUtils.getString(R.string.clearcachecancel), //取消
                            new String[]{StringUtils.getString(R.string.clearaddorsubmitsure)},//确定
                            null, mActivityInstance, AlertView.Style.Alert, new OnItemClickListener() {//
                        @Override
                        public void onItemClick(Object o, int position) {

                            if (position != AlertView.CANCELPOSITION) {

                                method_gainCompleteSubmitInfo_upLoad(extra_car_lossAdviceId);

                            }

                        }
                    });

                    mAlertView.setCancelable(true);
                    mAlertView.show();

                }
            });

        }


    }

    @Override
    protected void gainDatas() {

        if (NetworkUtils.isConnected()) {

            gainDatasFromServer();

        } else {
            //遮盖信息
            netWorkError();
        }

    }

    @Override
    protected void methodBack() {

        methodBackFinish();

    }


    //完成 按钮
    private void method_gainCompleteSubmitInfo_upLoad(Integer _ids) {

        //第一种方式
        //Integer[] idsArray = new Integer[]{Integer.parseInt(_ids)};
        //第二种方式
        Integer[] idsArray = new Integer[]{_ids};

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.ids, idsArray);

//        map.put(Parameterkey.status, ConsignStatus.STATUS_HAS_VERIFY.getIndex());//2:已审核 即审核通过状态

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_COMPLETERENEWALINSURANCE_URL);//
        addLogUpLoadInfo.setUrlPath(ApiService.completeRenewalInsurance_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .completeLossAdvice(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
//                .compose(CarRenewalFragment.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                    }
                })).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Throwable {

                        //TipDialog.show(StringUtils.getString(R.string.add_submit_success), WaitDialog.TYPE.SUCCESS);

                        EventCarInsuranceMain eventCarInsuranceMain = new EventCarInsuranceMain();
                        eventCarInsuranceMain.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_CAR_INSURANCE_MAIN_LIST);
                        EventBus.getDefault().post(eventCarInsuranceMain);

                        //通知主页列表刷新
                        EventCarInsuranceDetail eventCarInsuranceDetail = new EventCarInsuranceDetail();
                        eventCarInsuranceDetail.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_CAR_INSURANCE_DETAIL);
                        EventBus.getDefault().post(eventCarInsuranceDetail);

                        methodSubmitSuccess(mActivityInstance, null);

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                    }
                });
    }


    //接单 按钮
    private void method_gainTakeOrderSubmitInfo_upLoad(Integer _ids) {

        //传递参数的形式变成了如下格式：
//        {
//            "ids":["9"]
//        }

//        ArrayList<String> idsList = new ArrayList<>();
//        idsList.add(_ids);
        Integer[] idsArray = new Integer[]{_ids};
        //idsArray[0] = _ids;

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.ids, idsArray);//

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_RECEIVERENEWALINSURANCE);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.receiveRenewalInsurance_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(false);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .receiveLossAdvice(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
//                .compose(CarRenewalFragment.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        if (!TextUtils.isEmpty(serverMessage)) {
                            ToastUtils.showShort(serverMessage);
                        }

                    }
                })).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Throwable {

                        //TipDialog.show(StringUtils.getString(R.string.add_submit_success), WaitDialog.TYPE.SUCCESS);

                        EventCarInsuranceMain eventCarInsuranceMain = new EventCarInsuranceMain();
                        eventCarInsuranceMain.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_CAR_INSURANCE_MAIN_LIST);
                        EventBus.getDefault().post(eventCarInsuranceMain);

                        //通知主页列表刷新
                        EventCarInsuranceDetail eventCarInsuranceDetail = new EventCarInsuranceDetail();
                        eventCarInsuranceDetail.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_CAR_INSURANCE_DETAIL);
                        EventBus.getDefault().post(eventCarInsuranceDetail);

                        methodSubmitSuccess(mActivityInstance, null);

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        //
                    }
                });
    }

    private void gainDatasFromServer() {

//        latentCustomerId_upLoad = extra_lead_list_item_bean.getLatentCustomerId();

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.id, extra_car_lossAdviceId);

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETLOSSADVICELISTPAGE_GETBYID_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getLossAdviceListPage_getById_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_GET);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(false);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                //.getById(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue), MediaType.parse(ApiService.HEADER_JSON)))
                .getLossAdviceListPage_getById(extra_car_lossAdviceId)
                .compose(CarInsuranceDetailActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<CarInsuranceDetailBean>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        if (TextUtils.isEmpty(serverMessage)) {
                            ToastUtils.showShort(serverMessage);
                        }

                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {
                        loadingGone();
                        //
                    }
                }).subscribe(new Consumer<CarInsuranceDetailBean>() {
                    @Override
                    public void accept(CarInsuranceDetailBean carInsuranceDetailBean) throws Throwable {

                        //主要是顶部变动
                        if (carInsuranceDetailBean != null) {

                            //头部信息挨个填充
                            Delivery.getInstance().post(new Runnable() {
                                @Override
                                public void run() {

                                    //联系人姓名 填充
                                    CommUtils.setText(textViewPersonValueInsuranceDetail, carInsuranceDetailBean.getName());

                                    //该单据的状态文本
                                    CommUtils.setText(textViewPersonOrderStateInsuranceDetail, carInsuranceDetailBean.getStatusString());

                                    //填充 手机号信息
//                                    CommUtils.setText(textViewPersonPhoneValueInsuranceDetail, carInsuranceDetailBean.getPhone());
                                    CommUtils.setText(textViewPersonPhoneValueInsuranceDetail, StringCodeUtils.mobileEncrypt(carInsuranceDetailBean.getPhone()));

                                    textViewPersonPhoneValueInsuranceDetail.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            clickButton_toCallPhone(CarInsuranceDetailActivity.this, carInsuranceDetailBean.getPhone(), CallHistoryBusinessType.BUSINESSTYPE_10.getIndex());
                                        }
                                    });

                                    //车牌号
                                    CommUtils.setText(textViewCarNumberValueInsuranceDetail, carInsuranceDetailBean.getLicenseNo());

                                    //提交时间
                                    CommUtils.setText(textViewCreateTimeInsuranceDetail, carInsuranceDetailBean.getCreateTime());

                                    //状态的 数值格式
                                    String status = carInsuranceDetailBean.getStatus();

                                    //            status  0未接单  1已接单   2已完成
//               public enum CarRenewalStatus {
//                    status  0未接单  1已接单   2已完成
//                    STATUS_NOT_TAKEORDER("0", "未接单"),
//                    STATUS_HAS_TAKEORDER("1", "已接单"),
//                    STATUS_HAS_COMPLETE("2", "已完成");

                                    if (TextUtils.equals(status, CarRenewalStatus.STATUS_NOT_TAKEORDER.getIndex())) {

                                        CommUtils.setViewVisible(relativeLayoutTwoButtonInsuranceDetail);

                                        //接单 按钮 展示
                                        CommUtils.setViewVisible(roundTextViewViewTakeOrderInsuranceDetail);
                                        //完成 按钮  隐藏
                                        CommUtils.setViewGone(roundTextViewViewCompleteOrderInsuranceDetail);


                                    } else if (TextUtils.equals(status, CarRenewalStatus.STATUS_HAS_TAKEORDER.getIndex())) {

                                        CommUtils.setViewVisible(relativeLayoutTwoButtonInsuranceDetail);

                                        //接单 按钮 展示
                                        CommUtils.setViewGone(roundTextViewViewTakeOrderInsuranceDetail);
                                        //完成 按钮  隐藏
                                        CommUtils.setViewVisible(roundTextViewViewCompleteOrderInsuranceDetail);

                                    } else if (TextUtils.equals(status, CarRenewalStatus.STATUS_HAS_COMPLETE.getIndex())) {

                                        CommUtils.setViewGone(relativeLayoutTwoButtonInsuranceDetail);

                                    }

                                }
                            });

                        }
                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        //

                    }
                });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThreadInCarInsuranceDetail(EventCarInsuranceDetail eventCarInsuranceDetail) {

        if (eventCarInsuranceDetail != null) {

            if (eventCarInsuranceDetail.getMessage() == ExtraValue.EVENTBUS_EVENT_TO_REFRESH_CAR_INSURANCE_DETAIL) {

//                pagination_upLoad = Parameterkey.pageNum_default_first;
//                if (mDataResources != null && !mDataResources.isEmpty()) {
//                    mDataResources.clear();
//                }

//                if (consignMainAdapter != null) {
//                    consignMainAdapter.notifyDataSetChanged();
//                }

                gainDatasFromServer();

            }

        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void processExtraData() {

        //use the data received here
        Bundle bundle = this.getIntent().getExtras();

        if (bundle != null) {

//            LogUtils.d(ConstantSign.LOGCAT_NOMAL + extra_jumpfrom_where);

            extra_car_insurance_list_item_bean = bundle.getParcelable(ExtraKey.EXTRA_CAR_INSURANCE_LIST_ITEM_BEAN);

            if (extra_car_insurance_list_item_bean != null) {

                extra_car_lossAdviceId = extra_car_insurance_list_item_bean.getLossAdviceId();

            }

        }

    }
}